﻿using System;
using System.Collections.Specialized;
using System.IO;

using WebDavProcessor.Constants;
using WebDavProcessor.Interfaces;
using WebDavProcessor.Resources;

namespace WebDavProcessor.Methods
{
    public class WebDavPut : WebDavMethod
    {
        public WebDavPut(IWebDavRequest webDavRequest)
            : base(webDavRequest)
        {
        }
        public WebDavPut(string requestMethod, Uri requestUri, NameValueCollection requestHeaders, Stream requestInputStream)
            : base(requestMethod, requestUri, requestHeaders, requestInputStream)
        {
        }

        public override void ProcessRequest(IWebDavResponse webDavResponse, IWebDavResourceProvider resourceProvider)
        {
            WebDavResource resource;
            if (!(resourceProvider is IWebDavIOProvider))
            {
                WebDavMethod.SetError(webDavResponse, WebDavStatusCodes.NotImplemented);
                return;
            }
            try
            {
                resource = (resourceProvider as IWebDavIOProvider).Write(this.RequestUri.ToString(), this.InputStream);
                if (resource == null)
                {
                    WebDavMethod.SetError(webDavResponse, WebDavStatusCodes.NotImplemented);
                    return;
                }
                webDavResponse.StatusCode = resource.Status;
                webDavResponse.StatusDescription = WebDavStatusDescriptions.GetDescription(resource.Status);
            }
            catch (WebDavException e)
            {
                WebDavMethod.SetError(webDavResponse, e.StatusCode);
                return;
            }
            catch (Exception)
            {
                WebDavMethod.SetError(webDavResponse, WebDavStatusCodes.InternalServerError);
                return;
            }
        }
    }
}
